{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "6b226b1c",
   "metadata": {},
   "source": [
    "# 自动微分\n",
    "\n",
    "正如 :numref:`sec_calculus`中所说，求导是几乎所有深度学习优化算法的关键步骤。\n",
    "虽然求导的计算很简单，只需要一些基本的微积分。\n",
    "但对于复杂的模型，手工进行更新是一件很痛苦的事情（而且经常容易出错）。\n",
    "\n",
    "深度学习框架通过自动计算导数，即*自动微分*（automatic differentiation）来加快求导。\n",
    "实际中，根据设计好的模型，系统会构建一个*计算图*（computational graph），\n",
    "来跟踪计算是哪些数据通过哪些操作组合起来产生输出。\n",
    "自动微分使系统能够随后反向传播梯度。\n",
    "这里，*反向传播*（backpropagate）意味着跟踪整个计算图，填充关于每个参数的偏导数。\n",
    "\n",
    "## 一个简单的例子\n",
    "\n",
    "作为一个演示例子，(**假设我们想对函数$y=2\\mathbf{x}^{\\top}\\mathbf{x}$关于列向量$\\mathbf{x}$求导**)。\n",
    "首先，我们创建变量`x`并为其分配一个初始值。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "f120a340",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "device(type='mps')"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import torch\n",
    "\n",
    "torch.device('mps')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "b8702c3f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([0., 1., 2., 3.])"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x = torch.arange(4.0)\n",
    "x"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7a837887",
   "metadata": {},
   "source": [
    "[**在我们计算$y$关于$\\mathbf{x}$的梯度之前，需要一个地方来存储梯度。**]\n",
    "重要的是，我们不会在每次对一个参数求导时都分配新的内存。\n",
    "因为我们经常会成千上万次地更新相同的参数，每次都分配新的内存可能很快就会将内存耗尽。\n",
    "注意，一个标量函数关于向量$\\mathbf{x}$的梯度是向量，并且与$\\mathbf{x}$具有相同的形状。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "8d09f3ab",
   "metadata": {},
   "outputs": [],
   "source": [
    "x.requires_grad_(True)  # 等价于x=torch.arange(4.0,requires_grad=True)\n",
    "x.grad"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "5696cf5a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor(28., grad_fn=<MulBackward0>)"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y = 2 * torch.dot(x, x)\n",
    "y"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2b12eb8d",
   "metadata": {},
   "source": [
    "`x`是一个长度为4的向量，计算`x`和`x`的点积，得到了我们赋值给`y`的标量输出。\n",
    "接下来，[**通过调用反向传播函数来自动计算`y`关于`x`每个分量的梯度**]，并打印这些梯度。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "21e5c9e5",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([ 0.,  4.,  8., 12.])"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y.backward()\n",
    "x.grad"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "3bd796d3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([True, True, True, True])"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.grad == 4 * x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "ccf11b89",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([1., 1., 1., 1.])"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 在默认情况下，PyTorch会累积梯度，我们需要清除之前的值\n",
    "x.grad.zero_()\n",
    "y = x.sum()\n",
    "y.backward()\n",
    "x.grad"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "55ad6f96",
   "metadata": {},
   "source": [
    "## 非标量变量的反向传播\n",
    "\n",
    "当`y`不是标量时，向量`y`关于向量`x`的导数的最自然解释是一个矩阵。\n",
    "对于高阶和高维的`y`和`x`，求导的结果可以是一个高阶张量。\n",
    "\n",
    "然而，虽然这些更奇特的对象确实出现在高级机器学习中（包括[**深度学习中**]），\n",
    "但当调用向量的反向计算时，我们通常会试图计算一批训练样本中每个组成部分的损失函数的导数。\n",
    "这里(**，我们的目的不是计算微分矩阵，而是单独计算批量中每个样本的偏导数之和。**)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "6c1413a6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([0., 2., 4., 6.])"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 对非标量调用backward需要传入一个gradient参数，该参数指定微分函数关于self的梯度。\n",
    "# 本例只想求偏导数的和，所以传递一个1的梯度是合适的\n",
    "x.grad.zero_()\n",
    "y = x * x\n",
    "# 等价于y.backward(torch.ones(len(x)))\n",
    "y.sum().backward()\n",
    "x.grad"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2b33cfa0",
   "metadata": {},
   "source": [
    "## 分离计算\n",
    "\n",
    "有时，我们希望[**将某些计算移动到记录的计算图之外**]。\n",
    "例如，假设`y`是作为`x`的函数计算的，而`z`则是作为`y`和`x`的函数计算的。\n",
    "想象一下，我们想计算`z`关于`x`的梯度，但由于某种原因，希望将`y`视为一个常数，\n",
    "并且只考虑到`x`在`y`被计算后发挥的作用。\n",
    "\n",
    "这里可以分离`y`来返回一个新变量`u`，该变量与`y`具有相同的值，\n",
    "但丢弃计算图中如何计算`y`的任何信息。\n",
    "换句话说，梯度不会向后流经`u`到`x`。\n",
    "因此，下面的反向传播函数计算`z=u*x`关于`x`的偏导数，同时将`u`作为常数处理，\n",
    "而不是`z=x*x*x`关于`x`的偏导数。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "03781bbc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([True, True, True, True])"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.grad.zero_()\n",
    "y = x * x\n",
    "u = y.detach()  # 将y当做一个常数\n",
    "z = u * x\n",
    "\n",
    "z.sum().backward()\n",
    "x.grad == u"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4a677aa5",
   "metadata": {},
   "source": [
    "由于记录了`y`的计算结果，我们可以随后在`y`上调用反向传播，\n",
    "得到`y=x*x`关于的`x`的导数，即`2*x`。\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "aba7003d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([True, True, True, True])"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.grad.zero_()\n",
    "y.sum().backward()\n",
    "x.grad == 2 * x"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "24251d38",
   "metadata": {},
   "source": [
    "## Python控制流的梯度计算\n",
    "\n",
    "使用自动微分的一个好处是：\n",
    "[**即使构建函数的计算图需要通过Python控制流（例如，条件、循环或任意函数调用），我们仍然可以计算得到的变量的梯度**]。\n",
    "在下面的代码中，`while`循环的迭代次数和`if`语句的结果都取决于输入`a`的值。\n",
    "\n",
    "\n",
    "# z.sum().backward()什么要用sum() ,去看了源码才知道只有对标量输出它才会计算梯度，也就是说如果是个矩阵要先转化为标量才可以使用。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "f1b113f1",
   "metadata": {},
   "outputs": [],
   "source": [
    "def f(a):\n",
    "    b = a * 2\n",
    "    while b.norm() < 1000:\n",
    "        b = b * 2\n",
    "    if b.sum() > 0:\n",
    "        c = b\n",
    "    else:\n",
    "        c = 100 * b\n",
    "    return c\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "af6f1adb",
   "metadata": {},
   "outputs": [],
   "source": [
    "a = torch.randn(size=(), requires_grad=True)\n",
    "d = f(a)\n",
    "d.backward()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "9fa6bb78",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor(True)"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.grad == d / a"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "d2l",
   "language": "python",
   "name": "d2l"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.17"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
